export default class WebSocketModle {
	wsUrl = null; //服务器EndPoint地址

	heartbeatInterval = 5000; //心跳间隔
	heartbeatTimer = null; //心跳定时器

	reconnectInterval = 10000; //重连间隔
	reconnectTimer = null; //重连定时器

	isClosed = false; //连接是否主动关闭
	socketTask = null; //websocket对象

	constructor() {}

	initSocket(url) {
		if (url) {
			this.wsUrl = url;
		}
		if (this.socketTask) {
			//如果当前的对象不为空则先关闭
			this.socketTask.close();
			this.socketTask = null;
			//关闭心跳定时器
			clearInterval(this.heartbeatTimer);
		}

		//等待一个固定的时间，防止出现Websocket is closed before the connection is established 错误
		setTimeout(() => {
			console.log("wait 500ms then connect...")
		}, 500);

		this.socketTask = uni.connectSocket({
			url: this.wsUrl,
			success(data) {
				clearInterval(this.reconnectTimer); //连接成功就停止重连定时器
			},
			fail(err) {

			}
		});

		//连接服务器段成功后心跳发送
		this.socketTask.onOpen((res) => {
			clearInterval(this.reconnectTimer);
			this.heartbeatTimer = setInterval(() => {
				this.sendMsg('-heartbeat-')
			}, 3000);
		});

		//连接报错
		this.socketTask.onError((err) => {
			clearInterval(this.heartbeatTimer); //停止心跳发送
			if (!this.isClosed) {
				//如果不是主动关闭，则开启重连机制
				this.reconnect();
			}
		});

		//连接被关闭
		this.socketTask.onClose((e) => {
			clearInterval(this.heartbeatTimer); //停止心跳发送
			if (!this.isClosed) {
				//如果不是主动关闭，则开启重连机制
				this.reconnect();
			}
		});

		//收到消息
		this.socketTask.onMessage((res) => {
			let serverData = res.data;
			serverData && this.onReceive(serverData);
		})

	}

	//重连机制
	reconnect() {
		clearInterval(this.reconnectTimer); //先关闭重连定时器
		clearInterval(this.heartbeatTimer); //关闭心跳发送定时器
		this.socketTask && this.socketTask.close(); //关闭已有的连接
		this.socketTask = null;
		//开启重连定时器
		this.reconnectTimer = setInterval(() => {
			this.initSocket();
		}, 50000);
	}

	//接收到服务器段的数据
	onReceive(msg) {
		console.log("websocket msg received:" + msg);
		uni.$emit("websocket_msg_rcv", msg);
	}

	//向服务器端发送数据
	sendMsg(msg) {
		msg = JSON.stringify(msg);
		try {
			this.socketTask.send({
				data: msg
			});
		} catch (e) {
			if (isClosed) {
				return;
			} else {
				this.reconnect();
			}
		}
	}

	//关闭
	stop() {
		this.isClosed = true;
		clearInterval(this.heartbeatTimer);
		clearInterval(this.reconnectTimer);
		this.socketTask.close();
		this.socketTask = null;
	}
}